package com.xjj.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjj.entity.ResponseEntity;
import com.xjj.entity.Vote;
import com.xjj.service.VoteService;
import com.xjj.util.utils.DateTimeUtils;
import com.xjj.vo.VoteVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.xjj.utils.RedisCache.*;

/**
 * @author GH
 * @date 2022/10/20 14:12
 */
@RestController
@Slf4j
@Api(tags = "投票接口")
@RequestMapping("/vote/admin")
public class VoteController {
    @Resource
    private VoteService voteService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private RabbitTemplate rabbitTemplate;
    /**
     * @param voteVo:前端传过来的新投票需要将status设为0(即投票进行中)
     * @return ResponseEntity
     * @author GH
     * @description 添加一条投票
     * @date 2022/10/20 19:38
     */
    @PostMapping("/addVote")
    public ResponseEntity addVote(@RequestBody VoteVo voteVo){
        System.out.println(voteVo);
        voteService.addVote(voteVo);
        //添加完成后加入消息队列
        rabbitTemplate.convertAndSend("voteTimeOutExchange", "voteTimeOut", voteVo, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //  有死信队列：进入死信队列
                //  没有死信队列：消息丢失
                //  设置消息延迟发送的时间，安装延迟插件
                //  将vote的到期时间减去现在的时间获取毫秒值传入setDelay
                Long endTime = DateTimeUtils.toLongDateStr(voteVo.getVote().getEndTime());
                long nowTime = new Date().getTime();
                int delayTime = (int) (endTime - nowTime);
                log.debug("消息状态:{}","设置过期时间");
                message.getMessageProperties().setDelay(delayTime);
                log.debug("消息状态:{},{}毫秒后进入死信队列","进入交换机",delayTime);
                return message;
            }
        });
        return ResponseEntity.SUCCESS("添加投票成功",null);
    }

    /**
     * @param voteId: 要取消的投票
     * @return ResponseEntity
     * @author GH
     * @description 取消投票
     * @date 2022/10/20 19:39
     */
    @PutMapping("/cancelVote/{voteId}")
    public ResponseEntity cancelVote(@PathVariable Integer voteId){
        voteService.cancelVote(voteId);
        return ResponseEntity.SUCCESS("成功取消",null);
    }

    @PutMapping("/voteTimeOut/{voteId}")
    public ResponseEntity voteTimeOut(@PathVariable Integer voteId){
        boolean hasUpdate = voteService.voteTimeOut(voteId);
        return ResponseEntity.SUCCESS("投票结束",null);
    }

    @DeleteMapping("/deletelVote/{voteId}")
    public ResponseEntity deleteVote(@PathVariable Integer voteId){
        voteService.deleteById(voteId);
        return ResponseEntity.SUCCESS("成功删除",null);
    }

    /**
     * @param klassId: 班级id
     * @param current: 当前页,若第一次进入列表页面应将当前页赋0
     * @return ResponseEntity
     * @author GH
     * @description 分页查询该班级的所有投票
     * @date 2022/10/20 16:26
     */
    @GetMapping("/getVotes/{klassId}/{current}")
    public ResponseEntity getVotes(
            @PathVariable("klassId") Integer klassId,
            @PathVariable("current") Integer current) {
        Map votesMap = redisTemplate.opsForHash().entries(CACHE_VOTELIST_KEY+klassId+":"+current);
        log.debug("votesMap:{}",votesMap.isEmpty());
        if(votesMap.isEmpty()){
            if(current==0){
                Page<Vote> votePage = voteService.getVotes(klassId,1);
                Map<String, Object> votePageMap = BeanUtil.beanToMap(votePage);
                redisTemplate.opsForHash().putAll(CACHE_VOTELIST_KEY+klassId+":"+current,votePageMap);
                redisTemplate.expire(CACHE_VOTELIST_KEY,VOTELIST_TIMEOUT, TimeUnit.MINUTES);
                return new ResponseEntity<>(200,"ok",votePage);
            }else{
                Page<Vote> votePage = voteService.getVotes(klassId,current);
                Map<String, Object> votePageMap = BeanUtil.beanToMap(votePage);
                redisTemplate.opsForHash().putAll(CACHE_VOTELIST_KEY+klassId+":"+current,votePageMap);
                redisTemplate.expire(CACHE_VOTELIST_KEY,VOTELIST_TIMEOUT, TimeUnit.MINUTES);
                return new ResponseEntity<>(200,"ok",votePage);
            }
        }else {
            Page page = BeanUtil.mapToBean(votesMap,Page.class,false);
            return new ResponseEntity<>(200,"ok",page);
        }

    }

    /**
     * @param id: 要查询的那条投票的id
     * @return ResponseEntity<Vote>
     * @author GH
     * @description 查询该条投票详情
     * @date 2022/10/20 19:48
     */
    @GetMapping("/getDetails/{id}")
    public ResponseEntity<Vote> getDetails(@PathVariable Integer id){
        Map detailsMap = redisTemplate.opsForHash().entries(CACHE_VOTEDETAILS_KEY + id);
        if(detailsMap.isEmpty()){
            Vote vote = voteService.getDetailsById(id);
            Map<String, Object> beanToMap = BeanUtil.beanToMap(vote);
            redisTemplate.opsForHash().putAll(CACHE_VOTEDETAILS_KEY + id,beanToMap);
            redisTemplate.expire(CACHE_VOTEDETAILS_KEY,VOTEDETAILS_TIMEOUT, TimeUnit.MINUTES);
            return ResponseEntity.SUCCESS("ok",vote);
        }else {
            Vote vote = BeanUtil.mapToBean(detailsMap, Vote.class, false);
            return ResponseEntity.SUCCESS("ok",vote);
        }
    }



}
